﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.Model.OrderModels;
using CoreShop.PrintService;
using CoreShop.Services;
using FastMember;
using Loading;
using MySqlX.XDevAPI.Common;
using NPOI.SS.UserModel;
using NPOI.Util;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;
using static CoreShop.Library.GlobalEnumVars;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace CoreShop.App
{
    public partial class frmPaymentSet : UIForm
    {
        private List<corecmspayments> paymentsList = null;
        OpaqueCommand cmd1 = new OpaqueCommand();
        public frmPaymentSet()
        {
            InitializeComponent();
            dgvGoodsList.BackgroundColor = Color.White;
            dgvGoodsList.CellFormatting += DataGridView1_CellFormatting;
        }

        // 事件处理方法
        private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 检查是否是有效单元格
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                DataGridView dgv = sender as DataGridView;
                DataGridViewCell cell = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex];

                // 跳过新行
                if (dgv.Rows[e.RowIndex].IsNewRow) return;

                // 示例1：根据列索引设置不同列的颜色
                if (e.ColumnIndex < 3)
                {
                    cell.Style.BackColor = Color.SeaShell;
                }

                //支付
                DataGridViewRow row = dgvGoodsList.Rows[e.RowIndex];
                DataGridViewColumn col = dgvGoodsList.Columns[e.ColumnIndex];
                int payId = CommFunc.ConvertToInt32(row.Cells["id"].Value);
                // 示例："已审核"状态的行的"数量"列不允许修改
                if (col.Name == "rechargeUsed" &&
                    ((payId == (int)GlobalEnumVars.Payment.balancepay) ||
                    (payId == (int)GlobalEnumVars.Payment.coupon) ||
                    (payId == (int)GlobalEnumVars.Payment.points) ||
                    (payId == (int)GlobalEnumVars.Payment.douyin)))
                {
                    row.Cells[e.ColumnIndex].ReadOnly = true;
                    cell.Style.BackColor = Color.SeaShell;
                }
            }
        }

        private void frmfoodtask_Load(object sender, System.EventArgs e)
        {
            GetOrderingDetail();
        }

        private void GetOrderingDetail()
        {
            paymentsList = new corecmspaymentsService().AsQueryable()
                .Where(p=>p.isEnable == true).OrderBy(p=>p.sort,SqlSugar.OrderByType.Asc).ToList();
            dgvGoodsList.AutoGenerateColumns = false;
            this.binDetail.DataSource = paymentsList;
            this.dgvGoodsList.DataSource = this.binDetail;
        }
                
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private async Task<bool> SavePayments()
        {
            try
            {
                cmd1.ShowOpaqueLayer(pnl_Form, 125, true);
                foreach (var pay in paymentsList)
                {
                    //小于20为固定的支付，不能修改
                    if ((pay.id > 20) && (!string.IsNullOrEmpty(pay.content)))
                    {
                        BalanceTypeDataModel dataModel = pay.content.JsonToEntity<BalanceTypeDataModel>();
                        dataModel.posUsed = pay.posUsed;
                        dataModel.rechargeUsed = pay.rechargeUsed;
                        var result = await SystemApiUtil.SavePayments(dataModel);
                        if ((result != null) && (result.code != 200)) UIMessageBox.Show(result.msg);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message);
                return false;
            }
            finally { cmd1.HideOpaqueLayer(); }

        }

        private bool CheckValues()
        {
            int row = 1;
            foreach (var pay in paymentsList)
            {
                if ((pay.rechargeUsed == 1) &&
                    ((pay.id == (int)GlobalEnumVars.Payment.balancepay) ||
                    (pay.id == (int)GlobalEnumVars.Payment.coupon) ||
                    (pay.id == (int)GlobalEnumVars.Payment.points) ||
                    (pay.id == (int)GlobalEnumVars.Payment.douyin)))
                {
                    //UIMessageBox.Show($"第{row}行的[{pay.name}]不能选择为充值使用.");
                    //return false;
                    pay.rechargeUsed = 0;
                }
                row += 1;
            }
            return true; 
        }

        private async void btnSaveGoods_Click(object sender, EventArgs e)
        {
            paymentsList = this.binDetail.DataSource as List<corecmspayments>;
            if (!CheckValues()) return;
            await new corecmspaymentsService().InsertOrUpdateAsync(paymentsList);
            await SavePayments();
            ProcessUtil.GetSystemPayment();
            ShowInfoTip("保存完成。");
        }
    }
}
